package c07.immutable;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;

@Slf4j(topic = "c.DateFormatTest")
public class DateFormatTest {
    /*
    SimpleDateFormat存在线程安全问题
    可以使用JDK8引入的不可变线程安全对象DateTimeFormatter替代它
     */
    public static void main(String[] args) {
        testSimpleDateFormat();
//        testDateTimeFormatter();
    }

    private static void testSimpleDateFormat() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    log.debug("{}", sdf.parse("1951-04-21")); // java.lang.NumberFormatException: empty String
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static void testDateTimeFormatter() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    log.debug("{}", dtf.parse("1951-04-21"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
